<?php
/**
 * @name QuickAuth
 * @author Dave Blencowe
 * @author_url http://www.daveblencowe.com
 * @version 2.5
 * @license Free for use and modification, without credit given
 *
 * Quickauth authentication library for Codeigniter. Quickauth aims to provide
 * basic features with a minimal of front end content so that it's easy to drop
 * in to an application and customize to your needs
 */
class Quickauth
{

	var $ci;
	var $_tables = array (
		'users' => 'users'
	);
	var $cookie_time = 8640000;

	function __construct()
	{
		$this->ci =& get_instance();
		$this->ci->load->database();
		$this->ci->load->library('session');
		$this->ci->load->helper('cookie');
		
	}

	/**
	 * Log a user in using the supplied username and password combination
	 *
	 * @param <string> Supplied Username
	 * @param <string> Supplied Password
	 * @return <bool> True for a succesful login, False for no login + error
	 */
	function login($username, $password, $remember = FALSE)
	{
		$this->ci->db->where('username', $username);
		$this->ci->db->where('password', $this->encrypt($password));
		$q = $this->ci->db->get($this->_tables['users']);
		if ($q->num_rows() > 0) {
			$a = $q->row_array();
			$session_data = array (
				'userid' => $a['id']
			);

			$this->ci->session->set_userdata($session_data);
			
			// remember
			if($remember)
			{
				set_cookie(array(
					'name'   => 'userid',
					'value'  => $a['id'],
					'expire' => $this->cookie_time,
					));
			}
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Register a user. Data should be supplied in an array format using the
	 * structure specified below
	 *
	 * @param <array> Array, structured as follows: array('username', 'password');
	 * @return <bool> true
	 */
	function register($data)
	{
		$data['password'] = $this->encrypt($data['password']);

		$this->ci->db->insert($this->_tables['users'], $data);
		$id = $this->ci->db->insert_id();
		
		// add by Almond remeber user
		$session_data = array (
			'userid' => $id
		);

		$this->ci->session->set_userdata($session_data);
			
		return true;
	}

	/**
	 * Log a user out by destroying their session, then set a ui message and
	 * return
	 *
	 * @return <bool> True, to symbolise a succesful logout. 
	 */
	function logout()
	{
		$this->ci->session->sess_destroy('userid');
		if (get_cookie('userid'))
		{
			delete_cookie('userid');
		}
		$this->ci->session->sess_destroy();
		return true;
	}

	/**
	 * Reset a users password and email them the new password. Remember to set the $email_view
	 * variable and build a functioning view. To show the password in the email use echo $pass;
	 * WARNING: This function expects the users username to be in email format
	 * 
	 * @param <string> The users username
	 * @return <string> The new password
	 */
	function recover_password($user)
	{
		$chars = "abcdefghijkmnopqrstuvwxyz023456789";

	    srand((double)microtime()*1000000);
	    $i = 0;
	    $pass = '';
	    while ($i <= 12) {
	        $num = rand() % 33;
	        $tmp = substr($chars, $num, 1);
	        $pass = $pass . $tmp;
	        $i++;
	    }
	    
	    $newpass = $pass;
	    $encrypted_pass = $this->encrypt($pass);
	    
	    // Update the users password
	    $this->ci->db->where('username', $user);
	    $q = $this->ci->db->get($this->_tables['users']);
	    if ($q->num_rows() > 0) {
	    	$user_id = $q->row_array()->id;
	    	$user = $this->user($user_id);
	    	
	    	$this->ci->db->where('id', $user_id);
	    	$this->ci->db->set('password', $encrypted_pass);
	    	$this->ci->db->update($this->_tables['users']);
	    	
	    	/* disable by Almond
	    	// Email the users 
	    	$this->ci->load->library('email');
	    	$this->ci->email->to($user['username'], $user['firstname']." ".$user['lastname']);
	    	$this->ci->email->from($this->system_email);
	    	$this->ci->email->subject('Password Recovery');
	    	$data['pass'] = $pass;
	    	$message = $this->load->view($this->_email_view, $data, TRUE);
	    	$this->ci->email->message($message);
	    	$this->ci->email->send();
	    	*/
	    	return $pass;
	    } 
		return false;
	}

	/**
	 * Get the data on a user from the user table. Also parse their full name in
	 * to $data['name'] for convinience
	 *
	 * @param <int>   The individual users id. If blank will be for current user
	 * @return <array> Data for the user, or guest if not logged in
	 */
	function user($id = null)
	{
		if ($id == null) $id = $this->ci->session->userdata('userid') == '' ? $id = get_cookie('userid') : $this->ci->session->userdata('userid');
		// If the user is not signed in then assign them guest credentials and
		// return
		if (!$this->logged_in()) {
			$data = (object)'';
			$data->username = "guest";
			return $data;
		}
		// Get the specified users credentials from the users table and return
		// them
		$this->ci->db->where('id', $id);
		$q = $this->ci->db->get($this->_tables['users']);
		$data = $q->row();
		$data->username = $data->username;

		return $data;
	}

	/**
	 * Check to see if a user is logged in. If not then don't return anything
	 *
	 * @return <bool> Return True if user is logged in, else return nothing
	 */
	function logged_in()
	{
		$id = $this->ci->session->userdata('userid') == '' ? $id = get_cookie('userid') : $this->ci->session->userdata('userid');
		if ($id) {			
			return true;
		}
	}


	/**
	 * Encrypt a string (usually a password) ready for use within the library
	 * Uses SHA1 encryption against the Codeigniter encryption key
	 *
	 * @param <string> The string to be encrypted
	 * @return <string> The encrypted hash
	 */
	function encrypt($string)
	{
		$key = $this->ci->config->item('encryption_key');
		if (empty($key)) show_error('You must set the encryption key in your config file for Quickauth to function');
		$string = sha1($string.$key);
		return $string;
	}

	
}